package com.ls.herostory;

import com.ls.herostory.channel.handler.GameMsgDecoder;
import com.ls.herostory.channel.handler.GameMsgEncoder;
import com.ls.herostory.channel.handler.GameMsgHandler;
import com.ls.herostory.channel.handler.GameMsgRecognizer;
import com.ls.herostory.cmdhandler.CmdHandlerFactory;
import com.ls.herostory.mq.MqProducer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/10 11:48
 * @since
 */
public class MainServer {

    private final static Logger logger = LoggerFactory.getLogger(MainServer.class);

    public static void main(String[] args) {
        //
        CmdHandlerFactory.init();
        //
        GameMsgRecognizer.init();

        MqProducer.getInstance();

        //
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup(1);

        ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new HttpServerCodec(),
                                new HttpObjectAggregator(65535),
                                new WebSocketServerProtocolHandler("/websocket"),
                                new GameMsgDecoder(),
                                new GameMsgEncoder(),
                                new GameMsgHandler()
                        );
                    }
                });
        ChannelFuture bind = sb.bind(12345);

        try {
            if(bind.sync().isSuccess()){
                logger.info("服务器启动成功!");
            }

            bind.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }



}
